//
//  UIImageView+HWDUIImageView.m
//  huangwdUI
//
//  Created by 张露杰 on 17/4/7.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "UIImageView+HWDUIImageView.h"

@implementation UIImageView (HWDUIImageView)

- (instancetype)initWithFrame:(CGRect)frame image:(NSString *)imageName
{
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImage imageNamed:imageName];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame image:(NSString *)imageName contentMode:(UIViewContentMode)contentMode clipsToBounds:(BOOL)clipsToBounds
{
    self = [super initWithFrame:frame];
    if (self) {
        self.image = [UIImage imageNamed:imageName];
        self.contentMode = contentMode;
        self.clipsToBounds = clipsToBounds;
    }
    return self;
}

-(void)cutToCircle
{
    self.layer.masksToBounds = YES;
    if (self.frame.size.width != self.frame.size.height) {
        self.layer.cornerRadius = self.frame.size.width > self.frame.size.height?self.frame.size.height/2:self.frame.size.width/2;
    }
    else{
        self.layer.cornerRadius = self.frame.size.width/2;
    }
}

-(void)setFilterWithFilterName:(NSString *)filterName
{
    if (!self.image) {
        return;
    }
    //将UIImage转换成CIImage
    CIImage *ciImage = [[CIImage alloc] initWithImage:self.image];
    //创建滤镜
    CIFilter *filter = [CIFilter filterWithName:filterName keysAndValues:kCIInputImageKey, ciImage, nil];
    //已有的值不改变，其他的设为默认值
    [filter setDefaults];
    //获取绘制上下文
    CIContext *context = [CIContext contextWithOptions:nil];
    //渲染并输出CIImage
    CIImage *outputImage = [filter outputImage];
    //创建CGImage句柄
    CGImageRef cgImage = [context createCGImage:outputImage fromRect:[outputImage extent]];
    //获取图片
    UIImage *image = [UIImage imageWithCGImage:cgImage];
    //释放CGImage句柄
    CGImageRelease(cgImage);
    self.image = image;
}

@end
